package com.xiyu.service.repository.elder.register;

import com.xiyu.service.model.elder.info.ElderInfoFetcher;
import com.xiyu.service.model.elder.register.ElderTryLiving;
import com.xiyu.service.model.elder.register.ElderTryLivingFetcher;
import com.xiyu.service.model.elder.register.ElderTryLivingTable;
import com.xiyu.service.vo.elder.tryLiving.TryLivingQueryInput;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.Page;
import org.springframework.util.StringUtils;

import java.util.Optional;

public interface ElderTryLivingRepository extends JRepository<ElderTryLiving, Long> {
    ElderTryLivingTable elderTryLivingTable = ElderTryLivingTable.$;

    default Page<ElderTryLiving> pageQuery(TryLivingQueryInput inputVO){
        return sql().createQuery(elderTryLivingTable)
                .whereIf(StringUtils.hasText(inputVO.getElderNo()), () -> elderTryLivingTable.elder().elderNo().like(inputVO.getElderNo()))
                .whereIf(StringUtils.hasText(inputVO.getElderName()), () -> elderTryLivingTable.elder().name().like(inputVO.getElderName()))
                .whereIf(inputVO.getBeginTime() != null, () -> elderTryLivingTable.beginTime().between(inputVO.getBeginTime()[0], inputVO.getBeginTime()[1]))
                .whereIf(inputVO.getEndTime() != null, () -> elderTryLivingTable.endTime().between(inputVO.getEndTime()[0], inputVO.getEndTime()[1]))
                .orderBy(elderTryLivingTable.id().desc())
                .select(elderTryLivingTable.fetch(ElderTryLivingFetcher.$.allTableFields().elder(ElderInfoFetcher.$.allTableFields())))
                .fetchPage(inputVO.getPageNo() - 1, inputVO.getPageSize());

    }

    default Optional<ElderTryLiving> getById(Long id){
        return sql().createQuery(elderTryLivingTable)
                .where(elderTryLivingTable.id().eq(id))
                .select(elderTryLivingTable.fetch(ElderTryLivingFetcher.$.allTableFields().elder(ElderInfoFetcher.$.allTableFields())))
                .fetchOptional();
    }
}